package com.hongxun.budget.ui.view.ys;

import android.app.Fragment;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.EDrawLineEntityDao;
import com.hongxun.budget.ui.activity.ys.PullLineYsActivity;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.ui.fragment.ys.PointBasicCheckFragment;
import com.hongxun.budget.ui.view.BaseView;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.DPointEntity;
import com.hongxun.greenentity.ys.EDrawLineEntity;
import com.hongxun.greenentity.ys.EPointEntity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by admin on 2018/8/27.
 */

public class YsGanTaView extends BaseView implements View.OnClickListener {

    public static final int SET_LAXIAN = 0x7999;//设置拉线

    SpinnerAdapter<BDataDictionaryEntity> adapter1;
    SpinnerAdapter<BDataDictionaryEntity> adapter2;
    SpinnerAdapter<BMaterialEntity> adapter3;
    SpinnerAdapter<String> adapter5;
    SpinnerAdapter<BDataDictionaryEntity> adapter6;

    Spinner spinner, spinner2, spinner3, spinner5, spinner6;

    TextView laxian;
    EditText span;
    EditText jiaodu;

    List<EDrawLineEntity> inserts;//插入或者修改的拉线
    List<EDrawLineEntity> deletes;//删除的拉线

    public YsGanTaView(Fragment fragment) {
        super(fragment);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.view_ys_ganta;
    }

    @Override
    protected void initView() {
        super.initView();
        setProcess();
        inserts = new ArrayList<>();
        deletes = new ArrayList<>();
        //获取当前点位的拉线
        inserts.addAll(GreenDaoManager.getInstance().getmDaoSession().getEDrawLineEntityDao().queryBuilder()
                .where(EDrawLineEntityDao.Properties.PGuid.eq((String) SPUtils.get(context, "project_guid", ""))
                        , EDrawLineEntityDao.Properties.PPGuid.eq((String) SPUtils.get(context, "UUID", ""))
                        , EDrawLineEntityDao.Properties.DLDatastate.notEq("删除"))
                .build().list());
        laxian = getView(R.id.laxian);
        laxian.setOnClickListener(this);
        span = getView(R.id.span);
        jiaodu = getView(R.id.jiaodu);
        spinner = getView(R.id.spinner);//类型
        spinner2 = getView(R.id.spinner2);//高度
        spinner6 = getView(R.id.spinner6);//杆塔材质
        spinner3 = getView(R.id.spinner3);//导线型号
        spinner5 = getView(R.id.spinner5);//导线线数
        spinner.setAdapter(adapter1 = new SpinnerAdapter<BDataDictionaryEntity>(context, DBUtils.getBDataDictionaryEntities("gt_type"), spinner));
        spinner2.setAdapter(adapter2 = new SpinnerAdapter<BDataDictionaryEntity>(context, DBUtils.getBDataDictionaryEntities("gt_height"), spinner2));
        spinner3.setAdapter(adapter3 = new SpinnerAdapter<BMaterialEntity>(context, DBUtils.getYsMaterialEntities((String) SPUtils.get(context, "project_ys_guid", "")), spinner3));
        spinner5.setAdapter(adapter5 = new SpinnerAdapter<String>(context, Arrays.asList(context.getResources().getStringArray(R.array.daoxian)), spinner5));
        spinner6.setAdapter(adapter6 = new SpinnerAdapter<BDataDictionaryEntity>(context, DBUtils.getBDataDictionaryEntities("gt_material"), spinner6));
    }

    @Override
    public void initDefault() {
        DBUtils.setDefaultGtType(context, spinner);
        DBUtils.setDefaultGtHeight(context, spinner2);
        DBUtils.setDefaultGtMaterial(context, spinner6);
        if (SPUtils.get(context, "process", "").toString().equals("新增") && DBUtils.getYsIsDraw(context)) {
            DBUtils.setYsDefaultDxType(context, spinner3);
            DBUtils.setYsDefaultDxHeight(context, spinner5);
        }

        EPointEntity d = GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().load(SPUtils.get(context, "UUID", "").toString());
        if (d != null) updateInit(d);
    }

    EPointEntity d;

    @Override
    public boolean save(EPointEntity d) {
        d.setPPPropertyone(adapter1.getSelectedItem().getDKey());//杆塔类型
        d.setPPBar(Double.parseDouble(adapter2.getSelectedItem().getDValue()));//杆高
        d.setPPMaterial(adapter6.getSelectedItem().getDKey());//杆塔材质
        if (DBUtils.getYsIsDraw(context) && SPUtils.get(context, "process", "").equals("新增")) {//作图
            if (TextUtils.isEmpty(span.getText().toString())) {
                T.showLong(context, "档距不能为空");
                return false;
            }
            d.setPPInputspan((double) Math.round(Double.parseDouble(span.getText().toString()) * 100) / 100);//档距
            d.setPWGuid(adapter3.getSelectedItem().getGuid());//导线
            d.setPPLinenum(Integer.parseInt(adapter5.getSelectedItem()));//线数
            if (TextUtils.isEmpty(jiaodu.getText().toString())) {
                T.showLong(context, "角度不能为空");
                return false;
            }
            d.setPPAngle(Double.parseDouble(jiaodu.getText().toString()));//角度
            d.setPPAutospan(v);//计算获得的档距
        }
        d.setPPWirenum(inserts.size());
        this.d = d;
        return true;
    }

    @Override
    public void insertDB() {
        GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().insertOrReplace(d);
        GreenDaoManager.getInstance().getmDaoSession().getEDrawLineEntityDao().insertOrReplaceInTx(inserts);
        for (EDrawLineEntity d : deletes) {
            d.setDLDatastate("删除");
        }
        GreenDaoManager.getInstance().getmDaoSession().getEDrawLineEntityDao().updateInTx(deletes);
        //作图并且有上联点为的时候
        if (DBUtils.getYsIsDraw(context) && !d.getPPWorktype().equals("拆除") && !TextUtils.isEmpty(d.getPPUpguid()) && d.getPPInputspan() != 0) {//如果要作图，那个插入数据库的时候会自动生成导线数据到
            BMaterialEntity b = adapter3.getSelectedItem();
            DBUtils.addYsWire(context, b, d.getPPInputspan() * d.getPPLinenum());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.laxian:
                Intent intent = new Intent(context, PullLineYsActivity.class);
                intent.putExtra("lat", ((PointBasicCheckFragment) fragment).getLat());
                intent.putExtra("lgt", ((PointBasicCheckFragment) fragment).getLgt());
                intent.putExtra("insert", (Serializable) inserts);
                fragment.startActivityForResult(intent, SET_LAXIAN);
                break;
        }
    }

    Double v = 0.0;

    @Override
    public void setSpan(String beforeCode) {
        if (beforeCode == null) {
            span.setText("0");
        } else {
            EPointEntity EPointEntity = GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().load(beforeCode);
            LatLng before = new LatLng(EPointEntity.getPPInputlatitude(), EPointEntity.getPPInputlongitude());
            LatLng latLng = new LatLng(((PointBasicCheckFragment) fragment).getLat(), ((PointBasicCheckFragment) fragment).getLgt());
            v = (double) Math.round(AMapUtils.calculateLineDistance(before, latLng) * 100) / 100;
            span.setText(v + "");
        }
    }

    @Override
    public void setLatLng(Double oldLat, Double oldLgt, Double lat, Double lgt) {
        double a = lat - oldLat;
        double g = lgt - oldLgt;
        for (EDrawLineEntity d : inserts) {
            d.setDLLatitude(d.getDLLatitude() + a);
            d.setDLLongitude(d.getDLLongitude() + g);
        }
    }

    @Override
    public void result(int requestCode, int resultCode, Intent data) {
        inserts.clear();
        inserts.addAll((List<EDrawLineEntity>) data.getSerializableExtra("insert"));
        deletes.addAll((List<EDrawLineEntity>) data.getSerializableExtra("delete"));
        laxian.setText(inserts.size() + "");
        super.result(requestCode, resultCode, data);
    }

    @Override
    public void updateInit(Object o) {
        EPointEntity d = (EPointEntity) o;
        int i = 0;
        for (BDataDictionaryEntity b : DBUtils.getBDataDictionaryEntities("gt_material")) {
            if (b.getDKey().equals(d.getPPMaterial())) {
                spinner6.setSelection(i);
                break;
            }
            i++;
        }
        i = 0;
        for (BDataDictionaryEntity b : DBUtils.getBDataDictionaryEntities("gt_type")) {
            if (b.getDKey().equals(d.getPPPropertyone())) {
                spinner.setSelection(i);
                break;
            }
            i++;
        }
        i = 0;
        for (BDataDictionaryEntity b : DBUtils.getBDataDictionaryEntities("gt_height")) {
            if (Double.parseDouble(b.getDValue()) == d.getPPBar()) {
                spinner2.setSelection(i);
                break;
            }
            i++;
        }
        laxian.setText(d.getPPWirenum() + "");
        span.setText(d.getPPInputspan() + "");
        v = d.getPPAutospan() == null ? 0 : d.getPPAutospan();
        i = 0;
        for (BMaterialEntity b : DBUtils.getMaterialEntities(d.getPGuid())) {
            if (b.getGuid().equals(d.getPWGuid())) {
                spinner3.setSelection(i);
                break;
            }
            i++;
        }
        i = 0;
        for (String s : context.getResources().getStringArray(R.array.daoxian)) {
            if (Integer.parseInt(s) == (d.getPPLinenum() == null ? 0 : d.getPPLinenum())) {
                spinner5.setSelection(i);
                break;
            }
            i++;
        }
        jiaodu.setText(d.getPPAngle() + "");
    }

    @Override
    public void setProcess() {
        if (DBUtils.getYsIsDraw(context) && (SPUtils.get(context, "process", "").equals("新增")))//作图显示
            getView(R.id.draw_layout).setVisibility(View.VISIBLE);
        else
            getView(R.id.draw_layout).setVisibility(View.GONE);
    }
}
